package com.lzs.bootsafety.common.util.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzs.bootsafety.business.oss.service.SysConfigService;
import com.lzs.bootsafety.common.exception.LzsException;
import com.lzs.bootsafety.common.util.SpringContextAware;
import com.lzs.bootsafety.common.util.annotation.OperLog;
import com.lzs.bootsafety.common.util.aop.OperLogAspect;
import com.lzs.bootsafety.common.util.enums.SysConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;


public class LocationByIP {
    private static final Logger logger = LoggerFactory.getLogger(LocationByIP.class);
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.10 Safari/537.36";
    public static String  request(String ip){
        String address = "未知";
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        SysConfigService sysConfigService = SpringContextAware.getBean(SysConfigService.class);
        Map<String , Object> sysConfig = sysConfigService.getConfigs();
        String reqUrl = UrlUtils.getLocationByIp(ip, (String) sysConfig.get(SysConfig.BAIDU_API_AK.getKey()));
        final HttpURLConnection connection;
        try {
            URL url = new URL(reqUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("User-Agent", USER_AGENT);//Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)
            if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                JSONObject locationContent = JSON.parseObject(readInput(connection.getInputStream())).getJSONObject("content");
                if (locationContent.containsKey("address_detail")) {
                    JSONObject addressDetail = locationContent.getJSONObject("address_detail");
                    String province = addressDetail.getString("province");
                    String city = addressDetail.getString("city");
                    address = (StringUtils.isEmpty(province)? "" : province) +"|"+ (StringUtils.isEmpty(city) ? "" :city);
                }
                return address;
            } else {
                return address;
            }
        } catch (MalformedURLException e) {
            logger.info("请求失败："+reqUrl+e.getMessage());
        } catch (IOException e) {
            logger.info("IO异常："+reqUrl+e.getMessage());
        }
        return null;
    }
    protected static String readInput(final InputStream is) {
        if (null == is) {
            return null;
        }
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                logger.error("调用in.close Exception{}",e.getMessage());
            }
        }
        return content.toString();
    }
    public static void main(String[] args) {
        String location = LocationByIP.request("61.153.225.150");
        System.out.println(location);
    }

}
